from . import web
from flask import render_template, request, redirect, url_for, flash
# 用户系统
from app.formsjiaoyan.auth import RegisterForm, LoginForm, EmailForm, ResetPasswordForm
from app.models.base import db
from app.models.user import User
from flask_login import login_user, logout_user
from app.libs.email import send_mail

__author__ = '七月'


@web.route('/register', methods=['GET', 'POST'])
def register():
    form = RegisterForm(request.form)
    if request.method == 'POST' and form.validate():
        with db.auto_commit():
            user = User()
            user.set_attrs(form.data)
            db.session.add(user)  # 添加数据，在数据库中
        # db.session.commit() #提交数据库
        return redirect(url_for("web.login"))
    return render_template("auth/register.html", form=form)


@web.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm(request.form)  # 获取表单数据
    if request.method == 'POST' and form.validate():
        user = User.query.filter_by(email=form.email.data).first()
        if user and user.check_password(form.password.data):  # 将用户登录的信息写入cookie中
            login_user(user, remember=True)  # 把用户的票据写入到cookie中，非用户所有信息
            next = request.args.get('next')  # 获取连接？后面的参数与表单不一样，注意
            if not next or not next.startswith('/'):
                next = url_for('web.index')  # 当next为空的时候，重定向一个地址给它，这里需要做非法重定向，不然会被攻击如next指向其他网站地址
            print(next)
            return redirect(next)  # 重定向地址
        else:
            flash("账号不存在或者密码不对")

    return render_template("auth/login.html", form=form)


@web.route('/reset/password', methods=['GET', 'POST'])
def forget_password_request():  # 点击忘记密码到达的页面
    form = EmailForm(request.form)
    if request.method == 'POST':

        if form.validate():
            account_email = form.email.data
            # 借助first_or_404实现一个假如取不到值但是邮箱符合规范就返回404的异常，假如取到了就first（）,不过用first需要写入空值判断
            # try:
            user = User.query.filter_by(email=account_email).first_or_404()
            # send_mail这个使用第三方，比较缓慢，所以可以考虑异步
            send_mail(form.email.data, '重置你的密码', 'email/reset_password.html', user=user, token=user.generate_token())
            flash("重置密码邮件已发送至邮箱" + account_email + "您注意查收")
            # return redirect(url_for("web.login"))
            # except Exception as e:
            #     return render_template("404.html")
            # if not user:
            #     raise Exception()
    return render_template("auth/forget_password_request.html", form=form)


# 点击邮件里的链接
@web.route('/reset/password/<token>', methods=['GET', 'POST'])
def forget_password(token):
    form = ResetPasswordForm(request.form)
    if request.method == "POST" and form.validate():
        success = User.reset_password(token, form.password1.data)
        if success:
            flash("您的密码重置成功")
            return redirect(url_for("web.login"))
        else:
            flash("密码重置失败")
    return render_template('auth/forget_password.html', form=form)


@web.route('/change/password', methods=['GET', 'POST'])
def change_password():
    pass


@web.route('/logout')
def logout():
    logout_user()
    return redirect(url_for("web.index"))
